package com.lxq.smartsign.client.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.lxq.smartsign.client.MainActivity;
import com.lxq.smartsign.client.R;
import com.lxq.smartsign.client.util.ClientConfig;

import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends AppCompatActivity {

    private RequestQueue queue;
    private SharedPreferences ipPreferences;
    private SharedPreferences userPreferences;
    private EditText idV;
    private EditText passwordV;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        queue=Volley.newRequestQueue(this);
        idV=findViewById(R.id.id);
        passwordV=findViewById(R.id.password);
        ipPreferences=getSharedPreferences("ip_config",MODE_PRIVATE);
        userPreferences=getSharedPreferences("user",MODE_PRIVATE);
        initIp();

        findViewById(R.id.login).setOnClickListener(v -> {
            if (idV.getText().toString().equals("")||passwordV.getText().toString().equals("")){
                Toast.makeText(this, "请输入工号和密码", Toast.LENGTH_SHORT).show();
                return;
            }
            String url=ClientConfig.SERVER_URL+"/personnel_login";
            JSONObject param=new JSONObject();
            try {
                String androidId = android.provider.Settings.Secure.getString(this.getContentResolver(),
                        android.provider.Settings.Secure.ANDROID_ID);
                param.put("id",idV.getText().toString());
                param.put("password",passwordV.getText().toString());
                param.put("deviceId",androidId);
                if (androidId==null||androidId.equals("")){
                    Toast.makeText(this, "获取设备ID失败，无法登录", Toast.LENGTH_SHORT).show();
                    return;
                }
                JsonObjectRequest request=new JsonObjectRequest(Request.Method.POST,url,param,result->{
                    if (result.optInt("code")==1){
                        Toast.makeText(this,
                                "工号或密码错误，请重试。code="+result.optString("code"), Toast.LENGTH_SHORT).show();
                        return;
                    }else if(result.optInt("code")==3){
                        Toast.makeText(this,
                                "登录失败，此工号已关联其他设备，如需解除绑定，请联系管理员", Toast.LENGTH_LONG).show();
                        return;
                    }else if (result.optInt("code")==2){
                        AlertDialog dialog=new AlertDialog.Builder(this).create();
                        dialog.setMessage("此工号还未绑定任何设备，登录即同意该工号与该设备绑定，" +
                                "并且该工号将不能在其他设备登录。\n点击确定绑定设备。");
                        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", (dialog1, which) -> {

                            String bindUrl=ClientConfig.SERVER_URL+"/bind_device";
                            JsonObjectRequest bindRequest=new JsonObjectRequest(Request.Method.POST,bindUrl,param,result2->{
                                if (result2.optInt("code")==0){
                                    Toast.makeText(this,
                                            "绑定成功，请再次点击登录", Toast.LENGTH_SHORT).show();
                                }else{
                                    Toast.makeText(this,
                                            "绑定失败，请联系管理员处理", Toast.LENGTH_SHORT).show();
                                }
                            }, error -> Toast.makeText(this, "绑定失败", Toast.LENGTH_SHORT).show());
                            queue.add(bindRequest);
                        });
                        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", (dialog1, which) -> dialog.dismiss());
                        dialog.show();
                        return;
                    }
                    ClientConfig.ANDROID_ID=param.optString("deviceId");
                    Toast.makeText(this, "登录成功，欢迎您，"+result.optString("name"),
                            Toast.LENGTH_SHORT).show();
                    userPreferences.edit().putString("id",idV.getText().toString()).apply();
                    userPreferences.edit().putString("password",passwordV.getText().toString()).apply();
                    ClientConfig.USER_ID=idV.getText().toString();
                    ClientConfig.PASSWORD=passwordV.getText().toString();
                    ClientConfig.NAME=result.optString("name");
                    startActivity(new Intent(this, MainActivity.class));
                    finish();
                },error -> Toast.makeText(this, "登录失败:"+error.getMessage(), Toast.LENGTH_SHORT).show());
                queue.add(request);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        });

        findViewById(R.id.btn_setting).setOnClickListener(v->{
            AlertDialog settingDialog=new AlertDialog.Builder(LoginActivity.this).create();
            View dialogView=View.inflate(this,R.layout.dialog_network_setting,null);
            settingDialog.setTitle("设置服务器IP和端口");
            settingDialog.setView(dialogView);
            settingDialog.show();
            EditText ipV=dialogView.findViewById(R.id.server_ip);
            EditText portV=dialogView.findViewById(R.id.server_port);
            ipV.setText(ClientConfig.IP);
            portV.setText(ClientConfig.PORT);
            dialogView.findViewById(R.id.btn_test).setOnClickListener(v2->{
                String url="http://"+ipV.getText().toString()+":"+portV.getText().toString()+"/test";
                JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET,url,null,result->{
                    if (result.optInt("result_code")==0){
                        Toast.makeText(this, "连接成功", Toast.LENGTH_SHORT).show();
                    }
                },error -> Toast.makeText(this, "连接失败", Toast.LENGTH_SHORT).show());
                queue.add(request);
            });
            dialogView.findViewById(R.id.btn_save_net_config).setOnClickListener(v3->{
                ipPreferences.edit().putString("ip",ipV.getText().toString()).apply();
                ipPreferences.edit().putString("port",portV.getText().toString()).apply();

                ClientConfig.setUrl(ipV.getText().toString(),portV.getText().toString());

                settingDialog.dismiss();
            });
        });
    }

    private void success(){

    }

    private void initIp(){
        ClientConfig.setUrl(ipPreferences.getString("ip",""),
                ipPreferences.getString("port",""));
        idV.setText(userPreferences.getString("id",""));
        passwordV.setText(userPreferences.getString("password",""));
    }
}
